<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\helper\hash\Md5;
use think\Model;
use think\Request;
use think\response\Json;

class Pay00070 extends BasePay{

    const  secretKey = 'xSdfREHI3Y24a80n';


    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function order()
    {
        parent::order();
        $params = Request::instance()->param();
 
        $json_string = file_get_contents(env('PLATFORM.USD'));
        $config = json_decode($json_string, true);
        $usd  = $config[$this->order_array['goods_id']];
        if (empty($usd)) {
            mylog('计费点对应的美元金额找不到');
            throw new \Exception('计费点对应的美元金额找不到');
        }
        $coin = $usd['Mpay'];

        $payData = [
            'merchantNo'=>'M1828726347931283508', 
            'appKey'=>'A1829362443620282463', 
            "orderNo" => $this->order_array['id'],
            "amount" => $coin,
            'mobile'=>'18287263471',
            'email'=>'email@gmail.com',
            'firstName'=>'firstName',
            'lastName'=>'lastName',
            'callbackUrl'=>'https://pay.carcadefishing.com/home/pay00070/notify',
            // 'returnUrl'=>'https://pay.carcadefishing.com',
            // 'goods'=>'email:520155@gmail.com/name:tom/phone:7894561230/ip:8.219.187.96/payer:fdfafdfd',
        ];
        // var_dump($this->signData($payData));die;
        $sign = md5($this->signData($payData).self::secretKey);
        $payData['sign'] = $sign;
        // var_dump(json_encode($payData));die;

        $url = 'https://api-uat.v5pay.com/cgi/cashier/v2/payin';
        $response = $this->curl($url,json_encode($payData));

        if(empty(json_decode($response,true))){
            mylog('下单失败');
            exit(json_encode(['code'=>0,'msg'=>'','data'=>[]]));
        }
        $data = json_decode($response,true);
        if($data['code'] !='1000'){
            mylog('下单失败');
            exit(json_encode(['code'=>0,'msg'=>'','data'=>[]]));
        }

        (new \app\home\model\TradeLog)->where('id', $this->order_array['id'])->update(['dollPrice'=>$coin,'dollPriceType'=>'usd']);

        exit(json_encode(['code'=>1,'msg'=>'','data'=>$data]));
    }

    


    public function notify()
    {
        parent::notify();
        $params = $this->params;
        mylog($params);
        try{
            //验证签名
            $sign = md5($this->signData($params).self::secretKey);

            if($sign != strtolower($params['sign'])){
                throw new \Exception('sign false');
            }

            if($params['status'] != 2){
                throw new \Exception('status false');
            }
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$params['orderNo']])->find();
            if ($tradeLog['dollPrice'] != $params['amount']) {
                throw new \Exception('订单金额不一致' . ' 传参:' .  $params['amount'] . ' 实际:' . $tradeLog['dollPrice']);
            }
            
            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("00070 订单已经处理过了 订单id".$tradeLog['id']);
                exit('success');
            }
            
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            //facebook广告回传
            if(in_array($tradeLog->channel_id,(new AdFacebook())->channel_id)){
                $AdFacebook = new AdFacebook();
                $AdFacebook->pay($tradeLog->userid,$tradeLog->amount,$tradeLog->channel_id);
            }
            exit('success');
        }catch (\Exception $exception){
            mylog('00070-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            exit('FAIL');
        }

    }

    public function signData($data)
    {
        ksort($data);
        $tmp = [];
        foreach ($data as $k => $v) {
            if($k == 'sign'){
                continue;
            }
            $tmp[] = $k . '=' . $v;
        }
        $str = implode('&', $tmp);
        return $str;
    }

    
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);

        curl_close($ch);
        mylog($response);
        return $response;

        
    }
   
}
